﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace FormView.UI.PromptView
{
	public class PromptNumberView : IPromptViewControl
	{
		public static readonly string TagName = "number";

		public object GetValue(FrameworkElement element)
		{
			DockPanel dockPanel = element as DockPanel;
			TextBox tbx = dockPanel.Children[dockPanel.Children.Count - 1] as TextBox;
			return double.Parse(tbx.Text);
		}

		public FrameworkElement GetElement(PromptFormWindow win, string tipText, object value)
		{
			double val = 0;
			if (value != null && !double.TryParse(value.ToString(), out val))
			{
				throw new ArgumentException($"\"{value}\"不是一个number类型的值");
			}

			DockPanel dockPanel = new DockPanel();
			dockPanel.LastChildFill = true;
			dockPanel.Background = PromptFormWindow.DefaultBgColor;

			TextBlock textBlock = new TextBlock()
			{
				Padding = new Thickness(2),
				Foreground = PromptFormWindow.DefaultForeColor,
				Text = tipText,
				TextAlignment = TextAlignment.Center
			};
			DockPanel.SetDock(textBlock, Dock.Left);
			dockPanel.Children.Add(textBlock);

			TextBox textBox = new TextBox()
			{
				Padding = new Thickness(2),
				Foreground = PromptFormWindow.DefaultForeColor,
				Background = new SolidColorBrush(Colors.Transparent),
				Text = value == null ? "" : val.ToString()
			};
			InputMethod.SetIsInputMethodEnabled(textBox, false);
			textBox.PreviewTextInput += (sender, e) =>
			{
				string newText = textBox.Text + e.Text;
				double newVal;
				e.Handled = !double.TryParse(newText, out newVal);
			};
			dockPanel.Children.Add(textBox);

			return dockPanel;
		}

		public void OnRenderView(PromptFormWindow promptWindow, FrameworkElement element)
		{
			// ignore
		}
	}
}
